const cloud = require('wx-server-sdk')

cloud.init()

const SUCCESS = 0;
const BAD_PARAM = -1;

// (direction: string@enum('borrow', 'return'), id: PoolId | RecordId)
exports.main = async (event) => {
  const wx = cloud.getWXContext();
  const direction = event.direction;
  const id = event.id;

  if (id == null || direction == null || (direction != 'borrow' && direction != 'return')) {
    return {
      code: BAD_PARAM
    };
  }

  const db = cloud.database();

  const record = {
    id: id,
    time: Date.now(),
    state: 'new',
    openid: wx.OPENID,
    _type: direction
  };

  const res = await db.collection('deliveries').add({
    data: record
  });

  return {
    code: SUCCESS,
    id: res._id
  };
}
